package com.fenxiang.tieba.utils;

import com.fenxiang.tieba.PostMain;
import com.fenxiang.tieba.model.wrapper.BaseWrapper;

import javax.xml.bind.*;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by lixiang on 11/07/2017.
 */
public class XMLUtils {

    public static Logger logger = Logger.getLogger(XMLUtils.class.toString());
    static {
        logger.setLevel(Level.WARNING);
    }

    public static void saveToFile(BaseWrapper wrapper, String fileName, Class clazz){
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            String pathNow = XMLUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            String filePath = new File(pathNow).getParent() + "/conf/"+fileName;
            File file = new File(filePath);
            m.marshal(wrapper, file);
        } catch (PropertyException e) {
            logger.warning("propertyException");
            e.printStackTrace();
        } catch (JAXBException e) {
            logger.warning("JAXBException");
            e.printStackTrace();
        }
    }

    public static BaseWrapper loadFromFile(String fileName,Class clazz){
        try {

            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller um = context.createUnmarshaller();
            String pathNow = XMLUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            String filePath = new File(pathNow).getParent() + "/conf/"+fileName;
            File file = new File(filePath);
            return (BaseWrapper) um.unmarshal(file);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static BaseWrapper loadFromFile(File file,Class clazz){
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller um = context.createUnmarshaller();
            return (BaseWrapper) um.unmarshal(file);
        } catch (Exception e) { // catches ANY exception
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 向xml文件中添加一条数据
     * @param object  要添加的数据，实体类
     * @param fileName 要添加的文件名
     * @param clazz   要添加的实体类的wrapper类
     */
    public static void addToFile(Object object,String fileName,Class clazz){

        BaseWrapper wrapper = loadFromFile(fileName,clazz);
        List list = wrapper.getList();
        list.add(object);
        saveToFile(wrapper,fileName,clazz);

    }

    /**
     * 从XML文件中根据指定的主键(@identify)删除一条记录
     * @param identify 指定的主键
     * @param identifyNo 指定的要删除的值
     * @param fileName 要删除的文件名
     * @param clazz 要删除文件存储的实体类的wrapper类
     */
    public static  void deleteFromFile(String identify ,String identifyNo, String fileName,Class clazz){
        //先取到list
        BaseWrapper wrapper = loadFromFile(fileName,clazz);
        List list = wrapper.getList();
        try {
            Object object = list.get(0).getClass().newInstance();
            StringBuffer methodName = new StringBuffer("get");
            methodName.append(identify.substring(0,1).toUpperCase())
                    .append(identify.substring(1));

            for (Object obj : list) {
               String value = (String) object.getClass().getMethod(methodName.toString()).invoke(obj);
               if(value.equals(identifyNo)){
                   //匹配成功，从list中将其删掉
                   list.remove(obj);
                   saveToFile(wrapper,fileName,clazz);
                   return;
               }
            }

        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}
